package com.zhiyou100.taxi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhiyou100.taxi.dao.RoleMapper;
import com.zhiyou100.taxi.dao.UserMapper;
import com.zhiyou100.taxi.entity.Role;
import com.zhiyou100.taxi.entity.User;
import com.zhiyou100.taxi.entity.UserRole;
import com.zhiyou100.taxi.service.RoleService;
import com.zhiyou100.taxi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author zhaokuii11@163.com
 * @create 2021-11-27 10:24
 * @Description
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<Role> getAll() {
        return roleMapper.selectByExample(null);
    }

    @Override
    public PageInfo<Role> rolePage(Integer pageNum) {
        PageHelper.startPage(pageNum, 5);
        PageInfo<Role> rolePageInfo = new PageInfo<>(getAll());
        return rolePageInfo;
    }

    //删除 包括 tab_user_role/tab_user/tab_role_url/tab_url
    //删除 关于 tab_user id 的所有有关东西
    @Override
    public int deleteOneByPrimaryKeys(Set<String> set) {
        try {
            set.forEach(r -> {
                roleMapper.deleteByPrimaryKey(r);
            });
            return set.size();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public Role getOneByPrimaryKey(String roleId) {
        return roleMapper.selectByPrimaryKey(roleId);

    }

    @Override
    public int updateByPrimaryKey(Role role) {
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public int saveRole(Role role) {
        return roleMapper.insert(role);
    }

    @Autowired
    public UserMapper userMapper;

    @Override
    public Role getOneUnion(String roleId) {
        Role role = null;
        try {
            role = roleMapper.selectAndUserByPrimaryKey(roleId);
            List<User> userList = new ArrayList<>();
            List<UserRole> userRoles = role.getUserRoles();
            for (int i = 0; i < userRoles.size(); i++) {
                User temp = userMapper.selectByPrimaryKey(userRoles.get(i).getUserId());
                if (temp != null) {
                    userList.add(temp);
                }
            }
            role.setUser(userList);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return role;
    }

    @Override
    public String getPrimaryKey() {
        return "role_" + roleMapper.selectPrimaryKey();
    }
}
